<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
use App\WebSocket\WebSocketServer;
use React\EventLoop\Loop;
use React\Socket\SocketServer;
class StartWebSocketServer extends Command
{
    protected $signature = 'websocket:start';

    protected $description = '启动 Ratchet WebSocket 服务';

    public function handle()
    {
        $port = config('services.websocket.port', 8080);
        $host = config('services.websocket.host', '0.0.0.0');

        $loop = Loop::get();

        $socket = new SocketServer($host.':'.$port);

        new IoServer(
            new HttpServer(
                new WsServer(
                    new WebSocketServer($loop)
                )
            ),
            $socket,
            $loop
        );

        $this->info("WebSocket 服务已启动，监听地址: {$host}:{$port}");
        $this->info("服务器将接收客户端消息并每2秒向所有连接的客户端发送数据");

        $loop->run();
    }
}
